﻿//应用扩展
var AGL = {
    config: {
        NOTICEFREQUENCY: 30 * 1000,
        AVATARSIZE: {
            "small": 30,
            "normal": 45,
            "big": 90
        }
    },
    common: {
        copy: function(obj, txt, success) {
            var self = this;
            $(obj).each(function() {
                var content = txt;
                if (typeof ZeroClipboard == "undefined") return false;
                this.clip = null;
                if ($.isFunction(txt)) {
                    content = txt.call(this);
                }
                ZeroClipboard.setMoviePath(Cute.config.SCRIPTPATH + "ZeroClipboard.swf");
                this.clip = new ZeroClipboard.Client();
                this.clip.setHandCursor(true);
                this.clip.setText(content);
                this.clip.addEventListener('onComplete', success);
                $(window).resize(function() {
                    this.clip.reposition();
                } .bind(this));
                this.clip.glue(this);
                return this.clip;
            });
        },
        //ajax加载ajax/write里的页面，一样的内容，只会加载一次
        write: function(id, params, fn) {
            if (!id) return;
            if (arguments.length < 3) {
                cache = fn;
                fn = params;
                params = {};
            }
            var cachekey = "write" + id;
            if (params.cachekey) cachekey = params.cachekey; //设置cache的key值，默认为write + 文件ID
            if (!$(document).data(cachekey)) {
                Cute.api.get("write", $.extend({
                    id: id
                }, params || {}), function(html) {
                    if (html) {
                        $(document).data(cachekey, html);
                        fn(html);
                    }
                }, false, true);
            } else {
                fn($(document).data(cachekey));
            }
        },
        showMore: function(obj) {
            $(obj).next().show().end().prev().remove().end().remove();
        },
        errorAnimation: function(obj) {
            obj = $(obj);
            obj.stop(false, true).focus();
            var _o_bgcolor = obj.css("backgroundColor");
            obj.css({
                backgroundColor: "#FFC8C8"
            }).animate({
                backgroundColor: _o_bgcolor
            }, 1000, function(){
                this.style.cssText = this.style.cssText.replace(/background\-color[^;]+;/i,'');
            });
            return false;
        },
        showEmot: function(obj, parentEl) {
            var obj = $(obj);
            if (obj[0].dialog) {
                obj[0].dialog.toggle();
            } else {
                AGL.common.write(3, function(html) {
                    obj[0].dialog = new Cute.ui.dialog().tooltip("layer", "", {
                        content: '<div>' + html + '</div>',
                        className: "tooltip emot_dialog",
                        parentEl: parentEl,
                        pos: {
                            "top": function() {
                                return (parentEl ? obj.position().top : obj.offset().top) + obj.outerHeight() + 2;
                            },
                            "left": function() {
                                return (parentEl ? obj.position().left : obj.offset().left) - 1;
                            }
                        },
                        result: "result"
                    });
                    var form = obj.closest("form");
                    $(".d_emot a", obj[0].dialog.pannel).click(function(e) {
                        var _this = $(this);
                        Cute.common.insertSelection(form.find("textarea[name=content]")[0], _this.attr("rel"));
                        form.find("textarea[name=content]").trigger("keyup").css("color", "#000").trigger("keyup");
                        obj[0].dialog.hide();
                        e.preventDefault();
                        e.stopPropagation();
                    });
                    form.out("click.emot", function(e) {
                        if (!obj[0].dialog.pannel) {
                            form.unout("click.emot");
                            return;
                        }
                        if ($(this).has(e.target).length == 0) {
                            obj[0].dialog.hide();
                        }
                    }, true);
                });
            }
            return false;
        },
        blockSlide: function(options) {

            var self = this;
            var opt = $.extend(true, {
                width: 468, 	//宽度
                height: 80, 	//高度
                data: [], 	//广告列表，例：[{href:"",image:"",title:""}]
                interval: 5, //轮播间隔
                styleurl: ""	//特殊样式URL
            }, options);
            var iframe = $('<iframe />', {
                frameborder: 0,
                scrolling: "no",
                width: opt.width,
                height: opt.height
            }).css("display", "none").load(function() {
                var iDoc = iframe.contents();
                var _html = [];
                var _head = "\
					<style>\
					body{margin:0;padding:0;font-family:Arial;-webkit-text-size-adjust:none;}\
					img{border:0;}\
					.ad_list,.ad_ids{margin:0;padding:0;list-style:none;}\
					.ad_list li{ position:absolute;top:0;left:0;display:none;}\
					.ad_ids{position:absolute;bottom:10px; right:10px;z-index:50;}\
					.ad_ids li{float:left;margin-left:4px;}\
					.ad_ids li a{display:inline-block;font-size:9px;padding:2px 4px; border:1px solid #ddd;background-color:#eee;text-decoration:none;color:#888;zoom:1;}\
					.ad_ids li a:hover{text-decoration:none;}\
					.ad_ids li a.curr{border-color:#242424;color:#fff;background-color:#242424;}\
					</style>\
				";
                if (opt.styleurl) _head += '<link type="text/css" rel="stylesheet" href="' + opt.styleurl + '" />';
                iDoc.find("head").html(_head);
                var content = iDoc.find("body");
                if (opt.data.length > 0) {
                    $(this).show();
                    _html.push('<ul class="ad_list">');
                    $.each(opt.data, function(i, item) {
                        _html.push('<li><a href="' + item.Url + '" target="_blank"><img dynamic-src="' + item.Image + '" alt="' + item.Title + '" title="' + item.Title + '" width="' + opt.width + '" height="' + opt.height + '" /></a></li>');
                    });
                    _html.push('</ul>');
                    if (opt.data.length > 1) {
                        _html.push('<ul class="ad_ids">');
                        $.each(opt.data, function(i, item) {
                            _html.push('<li><a href="javascript:void(0)">' + (i + 1) + '</a></li>');
                        });
                        _html.push('</ul>');
                    }
                    $(this).contents().find("body").html(_html.join('')).find(".ad_ids a").click(function() {
                        setAdItem(parseInt($(this).text()) - 1);
                    });
                    setAdItem(0);
                }
                function setAdItem(num) {
                    if (num > opt.data.length - 1) {
                        num = 0;
                    }
                    var _ulList = iDoc.find(".ad_list");
                    var _ulIds = iDoc.find(".ad_ids");
                    _ulList.children("li").filter(":visible").stop(true, true).fadeOut(1000, function() {
                        $(this).css("z-index", 0);
                    }).end().eq(num).css("z-index", 1).stop(true, true).fadeIn(1000);
                    _ulList.find("img").filter(":eq(" + num + "),:eq(" + (num + 1 > opt.data.length - 1 ? 0 : (num + 1)) + ")").attr("src", function() {
                        var src = $(this).attr("dynamic-src");
                        $(this).removeAttr("dynamic-src");
                        return src;
                    });
                    if (opt.data.length > 1) {
                        _ulIds.find("a").removeClass().eq(num).addClass("curr");
                        clearTimeout(self.timer);
                        self.timer = setTimeout(function() {
                            setAdItem(num + 1);
                        }, opt.interval * 1000);
                    }
                }
            });
            return iframe;
        },
        editor: function(el, options) {
            Do("editor", function(K) {
                KindEditor.create(el, $.extend({
                    resizeType: 1,
                    themeType:"default",
                    themesPath: Cute.config.SCRIPTPATH + "editor/themes/",
                    pluginsPath: Cute.config.SCRIPTPATH + "editor/plugins/",
                    langPath : Cute.config.SCRIPTPATH + 'editor/lang/',
                    loadStyleMode: true,
                    filterMode: true,
                    urlType: "domain",
                    dialogAlignType: "",
                    htmlTags: {
                        font: ['color', 'size', 'face', '.background-color'],
                        span: ['style'],
                        a: ['href', 'target', 'style'],
                        embed: ['src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', 'align', 'allowscriptaccess', '/'],
                        img: ['src', 'width', 'height', 'border', 'alt', 'title', 'align', 'class', 'style', '/'],
                        hr: ['/'],
                        object: ['/'],
                        br: ['/'],
                        'p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6': []
                    },
                    items: ['fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                    'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
                    'insertunorderedlist', '|', 'emoticons', 'image', 'media', 'link','|','source']
                }, options || {}));
            });
        }
    },
    message: {
        post: function(user_id,tweets_id, nickname){
            var _self = this;
            new Cute.ui.dialog().ajax("给" + nickname + "发私信",{
                action:"message/dialog",
                params:{
                    user_id: user_id,
                    tweets_id: tweets_id
                },
                mask: true,
                open: {
                    callback: function() {
                        this.pannel.find("textarea[name=content]").focus();
                    }
                },
                buttons: [{
                    title: '发送',
                    type: 'main',
                    close: false,
                    func: function() {
                        var obj = this.pannel.find("textarea[name=content]");
                        if (Cute.form.isInputNull(obj)) {
                            AGL.common.errorAnimation(obj);
                            return false;
                        }
                        Cute.api.post("message/save", this.pannel.find("form").serialize(), function(json) {
                            if (json.status > 0) {
                                this.close();
                                new Cute.ui.dialog().suggest("私信已发出！");
                            }else{
                                alert(json.info);
                            }
                        }.bind(this));
                    }
                }, {
                    title: '取消',
                    type: 'cancel',
                    close: true
                }]
            });
        },
        check: function() {
            if (AGL.config.NOTICEFREQUENCY < 0) return false;
            var _this = this;
            var tm1 = new Date().getTime();
            var tm2 = tm1;
            var diff = 0;
            var _checkService = function(tp, fn) {
                if (Cute.Cookie.get(AGL.config.COOKIEPRE + "newcheckpm")) {
                    fn($.parseJSON(Cute.Cookie.get(AGL.config.COOKIEPRE + "newcheckpm")));
                } else {
                    if (tp) {
                        Cute.api.get("", {}, fn, false, true, {
                            global: false,
                            dataType: "jsonp",
                            url: AGL.config.PMSERVICE + "/Service.ashx?action=checkpm&userid=" + AGL.user.info.userid
                        });
                    } else {
                        Cute.api.get("checkpm", {}, fn, false, true, {
                            global: false
                        });
                    }
                }
            };
            _this.originalTitle = _this.originalTitle || document.title;
            _checkService(AGL.config.PMTYPE, function(json) {
                if (AGL.config.PMTYPE == 1) {
                    if (json.code != 0) return;
                } else {
                    if (json.code < 0) return;
                }
                var syspm = json.result.syspm.total ? json.result.syspm.total : 0;
                //把数据存入Cookie
                tm2 = new Date().getTime();
                diff = tm2 - tm1;
                //把数据存入Cookie - end
                $(window).unbind("scroll.messagetip resize.messagetip");
                var msg = $("#topMessage");
                var tips = $("#topMessageTips");
                if (tips.length == 0) return;
                _this.tipsFloat = _this.tipsFloat || $('<div id="topMessageFloat"><span class="layer_arrow l_arrow_up"><i></i></span><p></p></div>').appendTo(document.body);
                var tipsFloatText = _this.tipsFloat.children("p");
                $("#MyPm").html(json.result.pm > 0 ? '(' + json.result.pm + ')' : '');
                $("#SysPm").html(syspm > 0 ? '(' + syspm + ')' : '');
                $("#CommentPm").html(json.result.comment > 0 ? '(' + json.result.comment + ')' : '');
                $("#GuestBookPm").html(json.result.guestbook > 0 ? '(' + json.result.guestbook + ')' : '');
                var issysMsg = false;
                if (json.result.pm || syspm || json.result.guestbook || json.result.comment) {
                    var _html = [];
                    if (json.result.pm > 0) {
                        tips.attr("href", Cute.config.SITEURL + "message");
                        _html.push('<a href="' + Cute.config.SITEURL + 'message">' + json.result.pm + ' 条未读悄悄话</a>');
                    } else if (syspm > 0) {
                        tips.attr("href", Cute.config.SITEURL + "message/sys.aspx");
                        json.result.syspm.group_1 && _html.push('<p><a href="' + Cute.config.SITEURL + 'message/sys.aspx?type=1">好友请求(' + json.result.syspm.group_1 + '新)</a></p>');
                        json.result.syspm.group_2 && _html.push('<p><a href="' + Cute.config.SITEURL + 'message/sys.aspx?type=2">关注提醒(' + json.result.syspm.group_2 + '新)</a></p>');
                        json.result.syspm.group_3 && _html.push('<p><a href="' + Cute.config.SITEURL + 'message/sys.aspx?type=3">评论提醒(' + json.result.syspm.group_3 + '新)</a></p>');
                        json.result.syspm.group_4 && _html.push('<p><a href="' + Cute.config.SITEURL + 'message/sys.aspx?type=4">游戏互动(' + json.result.syspm.group_4 + '新)</a></p>');
                        json.result.syspm.group_5 && _html.push('<p><a href="' + Cute.config.SITEURL + 'message/sys.aspx?type=5">系统提醒(' + json.result.syspm.group_5 + '新)</a></p>');
                        issysMsg = true;
                    } else if (json.result.guestbook > 0) {
                        tips.attr("href", Cute.config.SITEURL + "message/gbook.aspx");
                        _html.push('<a href="' + Cute.config.SITEURL + 'message/gbook.aspx">' + json.result.guestbook + ' 条新留言</a>');
                    } else if (json.result.comment > 0) {
                        tips.attr("href", Cute.config.SITEURL + "message/comment.aspx");
                        _html.push('<a href="' + Cute.config.SITEURL + 'message/comment.aspx">' + json.result.comment + ' 条新评论</a>');
                    }
                    tips.show();
                    //var message = '您有 ' + (issysMsg ? _html.join("") : _html.join("、"));
                    var message = (issysMsg ? _html.join("") : _html.join("、"));
                    _this.tipsFloat.show().css("left", tips.offset().left - parseInt($(".layer_arrow", _this.tipsFloat).css("left")) + tips.width() / 2);
                    if (!_this.tipFloatTop) {
                        _this.tipFloatTop = parseInt(_this.tipsFloat.css("top"));
                    }
                    tipsFloatText.html(message);
                    clearInterval(_this.timer);
                    _this.timer = setInterval(function() {
                        if (!this.tipSwitch) {
                            this.tipSwitch = true;
                            document.title = "【新消息】" + this.originalTitle;
                        } else {
                            this.tipSwitch = false;
                            document.title = "【　　　】" + this.originalTitle;
                        }
                    } .bind(_this), 1000);
                    $(window).bind("scroll.messagetip", function() {
                        if ($(window).scrollTop() > _this.tipFloatTop - 10) {
                            if ($.browser.msie6) {
                                _this.tipsFloat.hide();
                                clearTimeout(_this.tipsFloat[0].timer);
                                _this.tipsFloat[0].timer = setTimeout(function() {
                                    _this.tipsFloat.css({
                                        "top": document.documentElement.scrollTop + 10
                                    }).fadeIn(100);
                                }, 600);
                            } else {
                                _this.tipsFloat.css({
                                    "position": "fixed",
                                    "top": 10
                                });
                            }
                        } else {
                            clearTimeout(_this.tipsFloat[0].timer);
                            _this.tipsFloat.css({
                                "position": "absolute",
                                "top": _this.tipFloatTop
                            }).show();
                        }
                    }).bind("resize.messagetip", function() {
                        _this.tipsFloat.css("left", tips.offset().left - parseInt($(".layer_arrow", _this.tipsFloat).css("left")) + tips.width() / 2);
                    });
                } else {
                    clearInterval(_this.timer);
                    $("#topMessageTips").hide();
                    _this.tipsFloat.hide();
                    document.title = _this.originalTitle;
                    _this.originalTitle = "";
                }
            });
            setTimeout(arguments.callee.bind(this), AGL.config.NOTICEFREQUENCY);
        }
    }
};

/*
* jQuery Color Animations
*/
(function(jQuery) {
    jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i, attr) {
        jQuery.fx.step[attr] = function(fx) {
            if (fx.state == 0) {
                fx.start = getColor(fx.elem, attr);
                fx.end = getRGB(fx.end);
            }
            fx.elem.style[attr] = "rgb(" + [
            Math.max(Math.min(parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
            Math.max(Math.min(parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
            Math.max(Math.min(parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
            ].join(",") + ")";
        }
    });
    function getRGB(color) {
        var result;
        if (color && color.constructor == Array && color.length == 3)
            return color;
        if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
            return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
        if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
            return [parseFloat(result[1]) * 2.55, parseFloat(result[2]) * 2.55, parseFloat(result[3]) * 2.55];
        if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
            return [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)];
        if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
            return [parseInt(result[1] + result[1], 16), parseInt(result[2] + result[2], 16), parseInt(result[3] + result[3], 16)];
        return "";
    }
    function getColor(elem, attr) {
        var color;
        do {
            color = jQuery.curCSS(elem, attr);
            if (color != '' && color != 'transparent' || jQuery.nodeName(elem, "body"))
                break;
            attr = "backgroundColor";
        } while (elem = elem.parentNode);
        return getRGB(color);
    };
})(jQuery);

//站点初始化
Do(function() {
    $('<div class="loading_lite" id="loading-lite" style="display:none">加载中，请稍候...</div>').appendTo(document.body).ajaxStart(function() {
        $(this).html('加载中，请稍候...').show();
    }).ajaxSuccess(function() {
        $(this).hide();
    }).ajaxError(function() {
        $(this).html('加载异常，请稍候刷新重试').show().delay(3000).fadeOut(1500);
    });
    $(window).on("beforeunload",function(){
        $("#loading-lite").stop().hide();
    });
    Do.ready("form",function() {
        if ($.browser.msie) Cute.form.bindFocus();
        Cute.form.bindDefault();
    });
    //返回顶部
    window.mainObj = window.mainObj ? window.mainObj : $("#main");
    if (mainObj.length > 0 && !$.browser.msie6) {
        var goTopObj = $('<div class="go_top"><a>▲回顶部</a></div>').appendTo(document.body).find("a").click(function() {
            $("html,body").animate({
                scrollTop: 0
            }, 0);
        }).end();
        $(window).bind("resize.gotop", function() {
            goTopObj.css("left", mainObj.outerWidth() + mainObj.offset().left - 1);
        }).bind("scroll.gotop", function() {
            if ($(window).scrollTop() > $(window).height() * 0.8) {
                if (goTopObj.is(":hidden")) goTopObj.fadeIn();
            } else {
                goTopObj.fadeOut();
            }
        }).triggerHandler("resize.gotop");
    }
});